package com.hjj.springboot.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hjj.springboot.config.LogType;
import com.hjj.springboot.config.SystemLogs;
import com.hjj.springboot.entity.*;
import com.hjj.springboot.service.IAdminService;
import com.hjj.springboot.service.INoticeService;
import com.hjj.springboot.util.JwtUtils;
import com.hjj.springboot.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/notice")
public class AdminNoticeController {

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private IAdminService adminService;

    @GetMapping("/findAll")
    public R findAll(){
        List<Notice> noticeList=noticeService.list(new QueryWrapper<Notice>().orderByDesc("upTime"));
        for (Notice notice : noticeList) {
            notice.setAdmin(adminService.getOne(new QueryWrapper<Admin>().eq("id",notice.getUid())));
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("notices", noticeList);
        return R.ok(map);
    }

    @PostMapping("/list")
    private R list(@RequestBody PageBean pageBean){
        String query=pageBean.getQuery().trim();
        Page<Notice> page=new Page<>(pageBean.getPageNum(),pageBean.getPageSize());
        Page<Notice> pageResult = noticeService.page(page,new QueryWrapper<Notice>().like(StringUtil.isNotEmpty(query),"content",query));
        for (Notice notice : pageResult.getRecords()) {
            notice.setAdmin(adminService.getOne(new QueryWrapper<Admin>().eq("id",notice.getUid())));
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",pageResult.getTotal());
        map.put("noticeList", pageResult.getRecords());
        return R.ok(map);
    }

    @GetMapping("/{id}")
    public R findById(@PathVariable(value = "id")Integer id){
        Notice notice=noticeService.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("notice",notice);
        return R.ok(map);
    }

    //更新公开状态
    @GetMapping("/updateState/{id}/state/{public}")
    public R updateState(@PathVariable(value = "id")Integer id,@PathVariable(value = "public")Boolean isPublic) {
        Notice notice = noticeService.getById(id);
        notice.setPublic(isPublic);
        if (isPublic){
            notice.setUpTime(new Date());
        }
        noticeService.saveOrUpdate(notice);
        return R.ok();
    }

    @PostMapping("/save")
    private R save(@RequestBody Notice notice){
        if(notice.getId()==null || notice.getId()==-1){
           Admin admin= JwtUtils.getCurrentAdmin();
           notice.setUid(admin.getId());
           notice.setUpTime(new Date());
           noticeService.save(notice);
        }else {
            noticeService.saveOrUpdate(notice);
        }
        return R.ok();
    }

    @GetMapping("/delete/{id}")
    private R delete(@PathVariable("id") Integer id){
        noticeService.removeById(id);
        return R.ok();
    }
    
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        noticeService.removeByIds(ids);
        return R.ok();
    }

    @GetMapping("/export")
    public void export(@RequestParam(required = false) String query, HttpServletResponse response)   throws Exception {
        String queryStr=query.trim();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("系统公告", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<Notice> noticeList = noticeService.list(new QueryWrapper<Notice>().like(StringUtil.isNotEmpty(queryStr),"content",query));
        EasyExcel.write(response.getOutputStream(),Notice.class)
                .sheet("系统公告")
                .doWrite(noticeList);
    }
}
